package Version3;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StaticResourceUtil {

    //根据相对路径，获取绝对路径地址

    /**
     * 内部先获取当前加载类的当前地址
     * 然后拼接路径
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path){
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        return absolutePath.replaceAll("\\\\","/")+path;
    }

    //读取文件，输出文件
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {

        //两部分：输出头部+输出文件【分页输出】
        int count=0;
        while (count==0){
            count=inputStream.available();
        }

        int resourceSize=count;

        //输出头部信息
        outputStream.write(HttpProtocolUtil.getHttpHeader200(count).getBytes());

        long written=0; //已经读取的文件数量
        int byteSize=1024; //每次读取1024;
        byte[] bytes=new byte[byteSize]; //每次读取1024 放入到缓存中

        while(written<resourceSize){

            //每次取数据都是精准的

            //当最后一次取值的时候，已经取值的数量+即将取值的数量大于总和
            if(written+byteSize>resourceSize){

                //重新调整 大小和数据包
                byteSize= (int) (resourceSize-written);
                bytes=new byte[byteSize];
            }

            inputStream.read(bytes);
            outputStream.write(bytes);

            outputStream.flush();
            written+=byteSize;
        }
    }
}
